package randomUtils

import (
	"math/rand"
	"time"
)

func NextInt(n int) int {
	rand.Seed(time.Now().UnixNano())
	return rand.Intn(n)
}

func WeightedRandomIndex(weights []int) int {
	totalWeight := 0
	for _, weight := range weights {
		totalWeight += weight
	}
	randWeight := rand.Intn(totalWeight)
	for i, weight := range weights {
		if randWeight < weight {
			return i
		}
		randWeight -= weight
	}
	return -1
}

func WeightedRandomMap(weightedMap map[interface{}]int) interface{} {
	if weightedMap == nil || len(weightedMap) == 0 {
		return nil
	}
	items := make([]interface{}, 0, len(weightedMap))
	weights := make([]int, 0, len(weightedMap))
	totalWeight := 0
	for item, weight := range weightedMap {
		items = append(items, item)
		weights = append(weights, weight)
		totalWeight += weight
	}
	randWeight := rand.Intn(totalWeight)
	for i, weight := range weights {
		if randWeight < weight {
			return items[i]
		}
		randWeight -= weight
	}
	return nil
}
